package restfuljobs

import org.grails.jaxrs.provider.DomainObjectNotFoundException

class JobApplicationResourceService {
    
    def create(JobApplication dto) {
        dto.save()
    }

    def read(def id) {
        def obj = JobApplication.get(id)
        if (!obj) {
            throw new DomainObjectNotFoundException(JobApplication.class, id)
        }
        obj
    }
    
    def readAll(long userId) {
    	def hql = "from JobApplication where applicant.id = " + userId
    	hql += " or jobListing.recruiter.id = " + userId
        
        JobApplication.findAll(hql)
    }
    
    def update(JobApplication dto, Long userId) {
		
        def obj = JobApplication.get(dto.id)
        if (!obj) {
            throw new DomainObjectNotFoundException(JobApplication.class, dto.id)
        }
		
		if (dto.status != obj.status) { //status changed
			def user = User.get(userId)
			if (!user) {
				throw new AccessDeniedException(JobApplication.class, userId)
			}
			
			switch (dto.status) {
				case JobApplication.Status.APPLICATION_RECEIVED:
				case JobApplication.Status.APPLICATION_WITHDRAWN:
					if (user.id != obj.applicant.id) {
						throw new AccessDeniedException(JobApplication.class, userId)
					}
					break
				
				case JobApplication.Status.APPLICATION_ACCEPTED:
				case JobApplication.Status.APPLICATION_REJECTED:
					if (user.id != obj.jobListing.recruiter.id) {
						throw new AccessDeniedException(JobApplication.class, userId)
					}
					break
			}
			
			obj.status = dto.status
			return obj
		}
		
        obj.properties = dto.properties 
        obj
    }
    
    void delete(def id) {
        def obj = JobApplication.get(id)
        if (obj) { 
            obj.delete()
        }
    }
    
}

